package com.sunseen.capacitormachine.modules.permission.factory;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sunseen.capacitormachine.R;
import com.sunseen.capacitormachine.databinding.FragmentSystemUndateBinding;
import com.sunseen.capacitormachine.common.BaseFragment;
import com.sunseen.capacitormachine.modules.permission.factory.adapter.ApkFileAdapter;
import com.sunseen.capacitormachine.modules.permission.factory.event.UpdateFileScanResult;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;


public class SystemUpdateFragment extends BaseFragment {

    static final String UDISK_PATH = "/mnt/usb_storage/USB_DISK2";

    private File curFile;

    @Override
    protected int setLayout() {
        return R.layout.fragment_system_undate;
    }

    @Override
    protected void onBindView(ViewDataBinding viewDataBinding) {
        EventBus.getDefault().register(this);
        FragmentSystemUndateBinding binding = (FragmentSystemUndateBinding) viewDataBinding;
        binding.btnScanFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(scanFileRun).start();
            }
        });
        binding.rvApks.setLayoutManager(new LinearLayoutManager(getContext()));
        apkFileAdapter = new ApkFileAdapter(R.layout.layout_item_apk_file);

        apkFileAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                curFile = ((File) adapter.getData().get(position));
                binding.tvCurApk.setText("已选择:" + curFile.getName());
            }
        });
        binding.rvApks.setAdapter(apkFileAdapter);
        binding.btnUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (curFile != null) {
                    if (dialog == null) {
                        initDialog();
                    }
                    textView.setText(curFile.getName());
                    dialog.show();
                } else {
                    Toast.makeText(_mActivity, "请点击选择要升级的文件", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private AlertDialog dialog;
    private TextView textView;

    private void initDialog() {
        RelativeLayout layout = (RelativeLayout) LayoutInflater.from(getContext()).inflate(R.layout.layout_selected_apk_name,null);


        textView = layout.findViewById(R.id.tv_selected_apk_name);
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle(getString(R.string.update_select_tip))
                .setView(layout)
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        openAPK(curFile.getAbsolutePath());
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
        dialog = builder.create();
    }

    private ApkFileAdapter apkFileAdapter;

    private Runnable scanFileRun = new Runnable() {
        @Override
        public void run() {
            File file = new File(UDISK_PATH);
            if (file.exists()) {
                File[] files = file.listFiles();
                if (files.length > 0) {
                    File usbRootFile = files[0];
                    File[] apkFiles = usbRootFile.listFiles(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String name) {
                            String[] nameSplit = name.split("\\.");
                            if (nameSplit.length > 0) {
                                Log.e("myLog", nameSplit[0] + "    " + nameSplit[nameSplit.length - 1]);
                            } else {
                                Log.e("myLog", "no split");
                            }

                            return nameSplit.length > 1
                                    && "apk".equals(nameSplit[nameSplit.length - 1])
                                    && nameSplit[0].startsWith("Capacitor");
                        }
                    });
                    if (apkFiles.length > 0) {
                        Log.e("myLog", "扫描到了apk文件");
                        EventBus.getDefault().post(new UpdateFileScanResult(2, apkFiles));
                    } else {
                        Log.e("myLog", "未扫描到apk文件");
                        EventBus.getDefault().post(new UpdateFileScanResult(1));
                    }
                } else {
                    Log.e("myLog", "未检测到U盘");
                    EventBus.getDefault().post(new UpdateFileScanResult(0));
                }
            } else {
                Log.e("myLog", "未检测根文件");
                EventBus.getDefault().post(new UpdateFileScanResult(0));
            }
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFileScanResult(UpdateFileScanResult event) {
        switch (event.getResult()) {
            case 0: {//未检测到U盘
                Toast.makeText(_mActivity, "未检测到U盘", Toast.LENGTH_SHORT).show();
            }
            break;
            case 1: {//未扫描到apk文件
                Toast.makeText(_mActivity, "未检测到apk文件", Toast.LENGTH_SHORT).show();
            }
            break;
            case 2: {//扫描到了apk文件
                List list = new ArrayList<File>();
                for (File f : event.getFiles()) {
                    list.add(f);
                }
                apkFileAdapter.setNewData(list);
            }
            break;

        }
    }

    /**
     * 安装apk
     *
     * @param fileAbsolutePath
     */
    private void openAPK(String fileAbsolutePath) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = new File(fileAbsolutePath);
        Uri data = Uri.fromFile(file);
        intent.setDataAndType(data, "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
